package com.example.cameraglrender.filter;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;

import com.example.cameraglrender.R;
import com.example.cameraglrender.util.GLImage;
import com.example.cameraglrender.util.OpenGlUtils;

public class FBOSoulFilter extends AbstractFBOFilter {

    private final int alpha;
    private int mFps;
    private float[] matrix = new float[16];
    int interval = 0;


    public FBOSoulFilter(Context mContext) {
        super(mContext, R.raw.fbo_soul_vertex, R.raw.fbo_soul_frag);
        alpha = GLES20.glGetUniformLocation(mProgramId, "alpha");
    }


    @Override
    public int onDrawFrame(int textureId) {
        interval++;

        if (interval > mFps) {
            interval = 1;
        }

        GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);

        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
        GLES20.glUseProgram(mProgramId);

        Matrix.setIdentityM(matrix, 0);

        GLES20.glUniformMatrix4fv(vMatrix, 1, false, matrix, 0);

        GLES20.glUniform1f(alpha, 1);


        //赋值vPosition
        mGlVertexBuffer.position(0);
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mGlVertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);

        //赋值vCoord
        mGlTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mGlTextureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);

        //赋值vMatrix
        Matrix.setIdentityM(matrix, 0);

        float scale = 1.0f + interval / (mFps * 2.f);

        Matrix.scaleM(matrix, 0, scale, scale, 0);

        GLES20.glUniformMatrix4fv(vMatrix, 1, false, matrix, 0);

        GLES20.glUniform1f(alpha, 0.1f + (mFps - interval) / 100.f);



        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
        //赋值vTexture
        GLES20.glUniform1i(vTexture, 0);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);

        return mFBOTextures[0];
    }

    public void setFPS(int fps) {
        mFps = fps;
    }
}
